<template>
  <Panel>
    <template #title>商品添加</template>
    <template>
      <el-form
        :model="goodsForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="mini"
      >
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="goodsForm.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goodsCate">
          <el-select v-model="goodsForm.goodsCate" placeholder="请选择活动区域">
            <el-option
              v-for="item in cates"
              :key="item.cateName"
              :label="item.cateName"
              :value="item.cateName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="goodsForm.price"
            :min="1"
            :max="10"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5000/goods/goods_img_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input type="textarea" v-model="goodsForm.desc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </template>
  </Panel>
</template>

<script>
import { allCates, addGoods } from '@/api/goods'
export default {
  data() {
    return {
      imageUrl: '',
      goodsForm: {
        goodsName: '',
        goodsCate: '',
        price: 0,
        desc: ''
      },
      rules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入价格', trigger: 'change' }],
        goodsCate: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        desc: [{ required: true, message: '请填写商品描述', trigger: 'blur' }]
      },
      goodsImg: '',
      cates: []
    }
  },
  created() {
    this.getCates()
  },
  methods: {
    async getCates() {
      const { categories } = await allCates()
      // console.log(data)
      this.cates = categories
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.goodsImg === '') {
            this.$message({
              type: 'warning',
              message: '请先上传图片'
            })
          }
          // 表单验证通过，图片也上传成功了，所以可以发起请求了
          const { code } = await addGoods({
            name: this.goodsForm.goodsName,
            category: this.goodsForm.goodsCate,
            price: this.goodsForm.price,
            imgUrl: this.goodsImg,
            goodsDesc: this.goodsForm.desc
          })
          // console.log(data)
          if (code === 0) {
            setTimeout(() => {
              this.$router.push('/goods/list')
            }, 1500)
          }
        } else {
          console.log(this.goodsForm.price)

          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // 把上传成功之后的图片地址存起来
      // this.$set(this, 'imgStr', res.imgUrl)
      this.goodsImg = res.imgUrl
    },
    beforeAvatarUpload(file) {
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // const isJPG = file.type === 'image/jpeg'
      // includes 数组的方法，判断当前的值是否包含在数组中
      const isBool = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isBool) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isBool && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 193px;
}
/deep/textarea {
  width: 300px;
  height: 90px;
}
// less 的穿刺写法
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
